from django import newforms as forms
from models import UserProfile
from django.contrib.auth.models import User
from django.contrib.auth import authenticate

class UserProfileForm(forms.Form):
    website = forms.URLField()
    feed_url = forms.URLField()
    
    def __init__(self, *args, **kwargs):
        self.profile = kwargs.pop('profile')
        super(UserProfileForm, self).__init__(*args, **kwargs)
    
    def clean_feed_url(self):
        feed_url = self.cleaned_data['feed_url']
        try:
            new_up = UserProfile.objects.exclude(id=self.profile.id).get(feed_url=feed_url)
            if new_up.user:
                raise forms.ValidationError(u'Feed already exists for another user.')
            else:    
                new_up.user = self.profile.user
                self.profile.delete()
                self.profile = new_up
                self.profile.save()
        except UserProfile.DoesNotExist:
            pass
        return feed_url    
    
    def save(self):
        self.profile.feed_url = self.cleaned_data['feed_url']
        self.profile.website = self.cleaned_data['website']
        self.profile.save()
        return self.profile

class FriendDeleteForm(forms.Form):
    def __init__(self, *args, **kwargs):
        friends = kwargs.pop('friends')
        super(FriendDeleteForm, self).__init__(*args, **kwargs)
        choices = [(f.id, f.get_display_name()) for f in friends]
        self.fields['friends'] = forms.MultipleChoiceField(choices=choices, widget=forms.CheckboxSelectMultiple)

class LoginForm(forms.Form):
    username = forms.CharField(max_length=128)
    password = forms.CharField(max_length=128, widget=forms.PasswordInput)
    
    def clean(self):
        super(LoginForm, self).clean()
        try:
            u = User.objects.get(username=self.cleaned_data['username'])
            username = u.username
        except User.DoesNotExist:
            raise forms.ValidationError("Invalid username.  Please try again.")
        user = authenticate(username = username, password = self.cleaned_data['password'])
        if user is not None:
            self.user = user
        else:
            raise forms.ValidationError("Invalid password. Please try again.")
        return self.cleaned_data

class RegisterForm(forms.Form):
    username = forms.CharField(max_length=128)
    email = forms.EmailField()
    password = forms.CharField(max_length=128, widget=forms.PasswordInput)
    confirm_password = forms.CharField(max_length=128, widget=forms.PasswordInput)
    
    def clean(self):
        super(RegisterForm, self).clean()
        try:
            u = User.objects.get(username=self.cleaned_data['username'])
            raise forms.ValidationError(u'Sorry, that username is already taken.')
        except User.DoesNotExist:
            pass
        if self.cleaned_data['password'] != self.cleaned_data['confirm_password']:
            raise forms.ValidationError(u'Passwords do not match.')
        return self.cleaned_data


class ConfirmFriendForm(forms.Form):
    def __init__(self, *args, **kwargs):
        friends = kwargs.pop('friends')
        rendered_friends = []
        for (url, web_list) in friends:
            rendered_friends.append((
                url,
                "Person with site(s) at: %s" % ", ".join([x for x in web_list]),
            ))
        super(ConfirmFriendForm, self).__init__(*args, **kwargs)
        self.fields['friends'] = forms.MultipleChoiceField(choices=rendered_friends, widget=forms.CheckboxSelectMultiple)
